package com.example.esp8266.Equipment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.OnBackPressedCallback;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.example.esp8266.Equipment.Equipment_Fragment.MainControl_Fragment;
import com.example.esp8266.Equipment.Task_Fragment.TaskList_Fragment;
import com.example.esp8266.Equipment.Task_Fragment.TaskRun_Fragment;
import com.example.esp8266.Library.Data.SensorData;
import com.example.esp8266.Library.MQTT.MQTT_Depend;
import com.example.esp8266.Main.MainActivity;
import com.example.esp8266.R;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;


public class Equipment_CtrlActivity extends AppCompatActivity
        implements View.OnClickListener,Fragment_CallBack,MqttCallback{

    private String device_name;
    private String previous_page = null,dataFromActivity = "free";
    private boolean MQTT_Status = false;
    private boolean Command_Status = false;
    private boolean Stm32_Connect_Status = false;
    private int layout_page = 0;
    String TAG = "MQTT_Client";
    MQTT_Depend mqtt;
    private double temperature;
    private double humidity;
    private int co2Concentration;
    private int pmIndex;
    private double lightIntensity;
    List<String> excludedMsgs = Arrays.asList("ALL.001", "ALL.010", "ALL.100");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_control);

        // 获取 SharedPreferences 对象，如果文件已存在则不创建新文件
        SharedPreferences sharedPref = getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor;
        editor = sharedPref.edit();
        if (!sharedPref.contains("previous_page")) {
            editor.putString("previous_page", null); // 初始化页面状态参数为 空
            editor.apply();
        }
        else if (!sharedPref.contains("Fan1_states")) {
            editor.putBoolean("Fan1_states",false);
            editor.putBoolean("Fan2_states",false);
            editor.putInt("Fan1_speed",0);
            editor.putInt("Fan2_speed",0);
            editor.apply();
        }
        String server_ip = sharedPref.getString("server_ip",null);
        String server_port = sharedPref.getString("server_port",null);

        device_name = sharedPref.getString("collection_1", null);
        TextView device_name_set = findViewById(R.id.ctrl_device_name);
        if (device_name != null) {
            device_name_set.setText(device_name.trim());//取得并设置当前要控制的设备
        }
        else {
            device_name_set.setText("未知设备");//取得并设置当前要控制的设备
        }

        ImageButton back_to_home = findViewById(R.id.Back_home_btn);
        back_to_home.setOnClickListener(this);//左上主界面按钮监听器

        MainControl_Fragment main_control_Fragment = new MainControl_Fragment();
        // 创建 Bundle 对象，用于存储参数args
        Bundle args = new Bundle();
        args.putString("target_device", device_name);
        // 将 Bundle 对象设置为 Fragment 的参数
        main_control_Fragment.setArguments(args);
        // 添加并初始化 Fragment 到指定的 View
        getSupportFragmentManager().beginTransaction()
                .add(R.id.control_fragment_view, main_control_Fragment)
                .commit();

        OnBackPressedCallback callback = new OnBackPressedCallback(true /* enabled by default */) {//返回键逻辑
            @SuppressLint("SetTextI18n")
            @Override
            public void handleOnBackPressed() {
                previous_page = sharedPref.getString("previous_page", null);
                if(previous_page == null){
                    Intent intent = new Intent(Equipment_CtrlActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish(); // 关闭当前Activity
                }
                else if (previous_page.contains("MainControlFragment")){
                    if (layout_page == 2) setContentView(R.layout.activity_control);
                    if (MQTT_Status){
                        TextView System_Status = findViewById(R.id.MQTT_status);
                        System_Status.setText("在线");
                        System_Status.setBackgroundResource(R.drawable.gradient_background_6); // 使用setBackgroundResource方法设置背景资源
                        if (Stm32_Connect_Status){
                            TextView STM32_Status = findViewById(R.id.STM32_status);
                            STM32_Status.setText("STM32在线");
                            STM32_Status.setBackgroundResource(R.drawable.gradient_background_2); // 使用setBackgroundResource方法设置背景资源
                        }
                    }
                    TextView device_name_set = findViewById(R.id.ctrl_device_name);
                    device_name_set.setText(device_name);//取得并设置当前要控制的设备
                    previous_page = null;
                    editor.putString("previous_page", null); // 重置页面状态参数为 空
                    editor.apply();
                    Bundle args = new Bundle();
                    args.putString("target_device", device_name);
                    MainControl_Fragment maincontrolFragment = new MainControl_Fragment();
                    // 将 args 对象设置为 Fragment 的参数
                    maincontrolFragment.setArguments(args);
                    replaceFragment(maincontrolFragment);
                } else if (previous_page.contains("TaskRun_Fragment")) {
                    Bundle args = new Bundle();
                    args.putString("back_info", "MainControlFragment");
                    TaskRun_Fragment autoRunFragment = new TaskRun_Fragment();
                    // 将 args 对象设置为 Fragment 的参数
                    autoRunFragment.setArguments(args);
                    replaceFragment(autoRunFragment);
                } else if (previous_page.contains("TaskList_Fragment")) {
                    // 获取 SharedPreferences 对象，如果文件已存在则不创建新文件
                    SharedPreferences sharedPref = getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
                    int taskGroup_id = sharedPref.getInt("task_groupId",-1);
                    String taskGroup_groupName = sharedPref.getString("task_groupName",null);

                    Bundle args = new Bundle();
                    args.putString("back_info", "TaskRun_Fragment");
                    args.putString("task_groupName", taskGroup_groupName); // 传递任务组名称
                    args.putInt("task_groupId", taskGroup_id); // 传递任务组ID

                    // 处理点击事件，切换到 TaskList_Fragment 并传递任务组ID
                    TaskList_Fragment taskListFragment = new TaskList_Fragment();
                    taskListFragment.setArguments(args);
                    replaceFragment(taskListFragment);
                }
            }
        };
        getOnBackPressedDispatcher().addCallback(this, callback);


        if (server_ip != null) {
            // 执行 MQTT 连接
            mqtt = new MQTT_Depend(server_ip, server_port, "PC_TEST", "SYSTEM", "PC_1", "sxc789426", this);
            mqtt.subscribeTopic("SENSOR_Rx",0);
        }

        // 以上为初始化
    }

    // mqtt回调函数
    @Override
    public void connectionLost(Throwable cause) {
        Log.d(TAG,"connectionLostException: " + cause.getMessage());
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void messageArrived(String topic, MqttMessage message) {
        String messageStr=new String(message.getPayload());
        if (Objects.equals(messageStr.trim(),"ESP8266_1.OK!")){
            MQTT_Status = true;
            TextView System_Status = findViewById(R.id.MQTT_status);
            System_Status.setText("在线");
            System_Status.setBackgroundResource(R.drawable.gradient_background_6); // 使用setBackgroundResource方法设置背景资源
        }
        else if (Objects.equals(messageStr.trim(),"STM32.Offline")){
            Stm32_Connect_Status = false;
            dataFromActivity = "offline";
            TextView STM32_Status = findViewById(R.id.STM32_status);
            STM32_Status.setText("STM32离线");
            STM32_Status.setBackgroundResource(R.drawable.gradient_background_1); // 使用setBackgroundResource方法设置背景资源
        }
        else if (Objects.equals(messageStr.trim(),"STM32.Online")){
            Stm32_Connect_Status = true;
            dataFromActivity = "online";
            TextView STM32_Status = findViewById(R.id.STM32_status);
            STM32_Status.setText("STM32在线");
            STM32_Status.setBackgroundResource(R.drawable.gradient_background_2); // 使用setBackgroundResource方法设置背景资源
        }
        else if (Objects.equals(messageStr.trim(),"Command.OK")){
            dataFromActivity = "free";
            Command_Status = false;
        }
        if (Objects.equals(topic, "SENSOR_Rx")){
            SensorData sensorData = new SensorData(messageStr);
            temperature = sensorData.getTemperature();
            humidity = sensorData.getHumidity();
            co2Concentration = sensorData.getCo2Concentration();
            pmIndex = sensorData.getPmIndex();
            lightIntensity = sensorData.getLightIntensity();
            //Log.i(TAG,sensorData.toString());
        }
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        Log.d("MQTT","deliveryComplete");
    }



    // 消息传递回调函数处理
    @Override
    public void sendMsgToActivity(String msg) {
        // 处理接收到的消息
        if(!Command_Status && MQTT_Status){
            if (msg != null && !excludedMsgs.contains(msg)) {
                Command_Status = true;
                mqtt.publishMessage("CTRL", msg, 0);
                dataFromActivity = "busy";
            }
            else if (msg != null){
                Log.i(TAG,"发送传感器指令");
                Command_Status = true;
                mqtt.publishMessage("SENSOR_Tx", msg, 0);
                dataFromActivity = "busy";
            }
        }
        Log.d("MainActivity", "Received message from Fragment: " + msg);
    }

    @Override
    public String getMsgFromActivity(String msg) {
        // 处理并返回数据给Fragment
        if (Command_Status){
            Toast.makeText(Equipment_CtrlActivity.this, "请等待上一条指令执行完毕", Toast.LENGTH_SHORT).show();
        }
        if(!Stm32_Connect_Status){
            Toast.makeText(Equipment_CtrlActivity.this, "网络连接异常", Toast.LENGTH_SHORT).show();
            dataFromActivity = "offline";
        }
        return dataFromActivity;
    }

    @SuppressLint("SetTextI18n")
    @Override//调用OnClickListener接口处理各种单击事件
    public void onClick(View v) {
        if (v.getId() == R.id.Back_home_btn){
            //切换主控制界面
            setContentView(R.layout.activity_control);
            previous_page = null;//重置页面缓存
            if (MQTT_Status){
                TextView System_Status = findViewById(R.id.MQTT_status);
                System_Status.setText("在线");
                System_Status.setBackgroundResource(R.drawable.gradient_background_6); // 使用setBackgroundResource方法设置背景资源
                if (Stm32_Connect_Status){
                    TextView STM32_Status = findViewById(R.id.STM32_status);
                    STM32_Status.setText("STM32在线");
                    STM32_Status.setBackgroundResource(R.drawable.gradient_background_2); // 使用setBackgroundResource方法设置背景资源
                }
            }
            TextView device_name_set = findViewById(R.id.ctrl_device_name);
            device_name_set.setText(device_name);//取得并设置当前要控制的设备

            Bundle args = new Bundle();
            args.putString("target_device", device_name);
            MainControl_Fragment maincontrolFragment = new MainControl_Fragment();
            // 将 args 对象设置为 Fragment 的参数
            maincontrolFragment.setArguments(args);
            replaceFragment(maincontrolFragment);
        }
    }

    //动态切换视图
    private void replaceFragment(Fragment fragment){
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.control_fragment_view,fragment);
        transaction.commit();
    }

    public void switch_view(int page){
        Log.i("Switch View","切换界面");
        if(page == 2){
            layout_page = page;
            setContentView(R.layout.activity_control_2);

            ImageButton back_to_home = findViewById(R.id.Back_home_btn);
            back_to_home.setOnClickListener(this);//左上主界面按钮监听器
        }
    }

    // 传感器信息反馈
    public double get_sensor_value(String sensor){
        switch (sensor) {
            case "Tem":
                return temperature;
            case "Hum":
                return humidity;
            case "Co2":
                return co2Concentration;
            case "Pm2":
                return pmIndex;
            case "Lux":
                return lightIntensity;
            default:
                break;
        }
        return 0;
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 执行必要的清理工作
        if(MQTT_Status) {
            Log.i(TAG,"Equipment,已断开与MQTT服务器的连接");
            mqtt.disconnect(MQTT_Status);
            MQTT_Status = false;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 在 Activity 生命周期结束时执行的操作
        if(MQTT_Status) {
            Log.i(TAG,"Equipment,已断开与MQTT服务器的连接");
            mqtt.disconnect(MQTT_Status);
            MQTT_Status = false;
        }
    }

}